package com.zhuannimei.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.zhuannimei.R;
import com.zhuannimei.dialog.EditTextDialog;
import com.zhuannimei.domain.OneShopProduct;
import com.zhuannimei.net.RequestServerData;
import com.zhuannimei.parser.LotteryDetailParser;
import com.zhuannimei.utility.UrlBank;
import com.zhuannimei.utility.WuLog;
import com.zhuannimei.utility.ZnmData;
import com.zhuannimei.utility.ZnmHttpParams;
import com.zhuannimei.view.XXButton;
import com.zhuannimei.view.XXRelativeLayout;

/**
 * oneGo this ui is oneGo's detail!U can here
 * 
 * @author Jack 2014-3-5
 * 
 * 
 */
public class LotteryDetailActivity extends BaseActivity implements
		OnClickListener {
	private static final String TAG = "LotteryDetailActivity";
	private XXButton goumai;
	public static final String SHOP_LUCKID = "shop_luckId";
	public static final String SHOP_CYID = "cyid";
	public static final String SHOP_PHASE = "phase";// 当前活动期数
	private ImageView adpic;
	private TextView product_meibi_tv;
	private TextView product_price_tv;
	private ProgressBar product_peo_num_pb;
	private TextView joinnum;
	private TextView allneednum;
	private TextView leftnum;
	private String luckId;
	private String cyId;
	private int mPhase = 1;
	private TextView mMebi;
	private XXRelativeLayout xxJoinList;
	private LinearLayout ll_detail;
	private LinearLayout ll_none_detil;
	private ImageView none_refresh;
	private EditTextDialog mEditTextDialog;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.lottery_fragment);
		luckId = getIntent().getStringExtra(SHOP_LUCKID);
		cyId = getIntent().getStringExtra(SHOP_CYID);
		String mum = getIntent().getStringExtra(SHOP_PHASE);
		WuLog.i(TAG, ""+mum);
		if (!TextUtils.isEmpty(mum)) {
			mPhase = Integer.parseInt(mum);
		}
		initView();
		setListener();
		getPhaseShopDetail(mPhase);
//		getPhaseNum();
		
	}

	private void initView() {
		// 购买
		goumai = (XXButton) findViewById(R.id.product_goumai_btn);
		// 大图
		adpic = (ImageView) findViewById(R.id.adpic);
		// 商品大标题 期数+商品名称+商品描述
		product_meibi_tv = (TextView) findViewById(R.id.product_meibi_tv);
		// 商品市场价格
		product_price_tv = (TextView) findViewById(R.id.product_price_tv);
		// 进度条
		product_peo_num_pb = (ProgressBar) findViewById(R.id.product_peo_num_pb);
		// 参与人数
		joinnum = (TextView) findViewById(R.id.joinnum);
		// 总人数
		allneednum = (TextView) findViewById(R.id.allneednum);
		// 剩余人数
		leftnum = (TextView) findViewById(R.id.leftnum);
		// 需要消耗的积分
		mMebi = (TextView) findViewById(R.id.product_app_point);
		//参与人记录
		xxJoinList = (XXRelativeLayout) findViewById(R.id.rl_lottery_history);
		//控制显示及隐藏
		ll_detail = (LinearLayout) findViewById(R.id.ll_detail);
		ll_none_detil = (LinearLayout) findViewById(R.id.none_detail_ll);
		none_refresh = (ImageView) findViewById(R.id.iv_none_refresh);
	}
	
	private void showDetailView(){
		ll_detail.setVisibility(View.VISIBLE);
		ll_none_detil.setVisibility(View.GONE);
	}
	
	private void showNoneDetailView(){
		ll_detail.setVisibility(View.GONE);
		ll_none_detil.setVisibility(View.VISIBLE);
	}

	private void setData(OneShopProduct osp) {
		// 商品大标题
		// product_meibi_tv.setText(price + "妹币");
		product_meibi_tv.setText("("+osp.getPhase()+"期)"+osp.getTitle()+" "+osp.getDescribe());
		 imageLoader.displayImage(UrlBank.getServerIp()+osp.getPicture(), adpic, options);
		 product_price_tv.setText("￥:" +osp.getPrice()+ "元");
		 product_peo_num_pb.setMax(Integer.parseInt(osp.getTotal()));
		 product_peo_num_pb.setProgress(Integer.parseInt(osp.getJoins()));
		 joinnum.setText(osp.getJoins());
		 allneednum.setText(osp.getTotal());
		 leftnum.setText(osp.getLast());
		 mMebi.setText(osp.getBuyed()+"妹币/1人次");
		 
		 //根据剩余人数来判断 购买按钮是否可以继续购买
		 if("0".equals(osp.getLast())){
			 goumai.setClickable(false);
			 goumai.setBackgroundResource(R.drawable.gray_bg1);
			 goumai.setText("很遗憾，已经抢光了！");
		 }else{
			 goumai.setClickable(true);
			 goumai.setBackgroundResource(R.drawable.title_right_bg_press);
			 goumai.setText("立即购买");
		 }
	}

	private void setListener() {
		goumai.setOnClickListener(LotteryDetailActivity.this);
		xxJoinList.setOnClickListener(this);
		none_refresh.setOnClickListener(this);
	}

	/**
	 * 从网络上获取期数
	 */
	private int getPhaseNum() {
		RequestParams mParams = ZnmHttpParams.getDefaultRequestParams();
		mParams.addBodyParameter("cgyId", cyId);
		RequestServerData.getPhaseNum(mParams, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				WuLog.i(TAG, "" + responseInfo.result);
				try {
					JSONObject jo = new JSONObject(responseInfo.result);
					String code = jo.optString("code");
					if ("0".equals(code)) {
						String num = jo.optString("result");
						mPhase = Integer.parseInt(num);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {
				WuLog.i(TAG, "---" + error.getExceptionCode());
			}
		});
		return mPhase;
	}

	@Override
	protected void onStart() {
		super.onStart();
		mTitlePane.getLeftButton().setVisibility(View.VISIBLE);
		mTitlePane.getRightButton().setVisibility(View.VISIBLE);
		mTitlePane.setLeftButtonTextAndListener("返回", new OnClickListener() {
			@Override
			public void onClick(View v) {
				LotteryDetailActivity.this.finish();
			}
		});
		mTitlePane.setRightButtonTextAndListener("往期", new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mEditTextDialog = new EditTextDialog(LotteryDetailActivity.this);
				mEditTextDialog.setTitle("查询往期活动,共("+mPhase+")期");
				mEditTextDialog.setButton("取消",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								mEditTextDialog.cancel();
							}
						}, "确认", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								String text = mEditTextDialog.getText();
								if (text == null) {
									mEditTextDialog.requestFocus();
									showCustomToast("期数不能为空");
								} else {
									int nn = Integer.parseInt(text);
									if (nn <= mPhase) {
										showCustomToast("开始查询");
										getPhaseShopDetail(nn);
										mEditTextDialog.dismiss();
									} else {
										showCustomToast("没有当前期数");
									}
								}
							}
						});
				mEditTextDialog.show();
			}
		});
		mTitlePane.setTitle("商品详情");
	}

	// 查询某期数的一元购详情数据
	private void getPhaseShopDetail(int phase) {
		showLoadingDialog("正在查询详情……");
		RequestParams mParams = ZnmHttpParams.getDefaultRequestParams();
		WuLog.i(TAG, "cyID"+cyId+phase);
		mParams.addBodyParameter("cgyId", "" + cyId);
		mParams.addBodyParameter("phase", "" + phase);
		RequestServerData.getLuckDetail(mParams, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				WuLog.i(TAG, "" + responseInfo.result);
				try {
					OneShopProduct osp = new LotteryDetailParser()
							.parseJSON(responseInfo.result);
					WuLog.i(TAG, "解析后的数据osp==" + osp.getTitle());
					setData(osp);
					showDetailView();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				dismissLoadingDialog();
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				WuLog.i(TAG, "" + error.getExceptionCode());
				showCustomToast("网络不给力");
				showNoneDetailView();
				dismissLoadingDialog();
			}
		});
	}

	/**
	 * 参与一元购
	 */
	private void sendOneShop(final int num) {
		RequestParams mParams = ZnmHttpParams.getDefaultRequestParams();
		mParams.addBodyParameter("userId", ""
				+ ZnmData.getUserData().getUserUserId());
		mParams.addBodyParameter("luckId", "" + luckId);
		mParams.addBodyParameter("number", "" + num);
		WuLog.i(TAG, "luckId==" + luckId + "num==" + num);
		RequestServerData.getLuck(mParams, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					WuLog.i(TAG, responseInfo.result+";userId="+ZnmData.getUserData().getUserUserId());
					JSONObject jo = new JSONObject(responseInfo.result);
					if("0".equals(jo.optString("code"))){
						showCustomToast("成功购买"+num+"个幸运码");
						//获取用户总积分
						String result = jo.optString("result");
						WuLog.i(TAG, ""+result);
						ZnmData.getUserData().saveUserPoint(result);
						WuLog.i(TAG, ""+ZnmData.getUserData().getUserPoint());
						//刷新下界面
						getPhaseShopDetail(mPhase);
					}else if("12".equals(jo.optString("code"))){
						showCustomToast("对不起,您的积分不足……");
					}else if("14".equals(jo.optString("code"))){
						showCustomToast("参加人数已经满了");
					}
				} catch (JSONException e) {
					e.printStackTrace();
					showCustomToast("网络不给力");
				}
				dismissLoadingDialog();
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				WuLog.i(TAG,
						"" + error.toString() + ";;"
								+ error.getLocalizedMessage() + msg);
				showCustomToast("失败" + error.getExceptionCode() + msg);
				dismissLoadingDialog();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.product_goumai_btn:
			mEditTextDialog = new EditTextDialog(LotteryDetailActivity.this);
			mEditTextDialog.setTitle("购买");
			mEditTextDialog.setButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							mEditTextDialog.cancel();
						}
					}, "确认", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							String text = mEditTextDialog.getText();
							if (text == null) {
								mEditTextDialog.requestFocus();
								showCustomToast("请输入要购买的数量");
							} else {
								int num = Integer.parseInt(text);
								showLoadingDialog("购买中");
								sendOneShop(num);
								mEditTextDialog.dismiss();
							}
						}
					});
			mEditTextDialog.show();
			break;
		 case R.id.rl_lottery_history:
		 // 跳转到
		 Intent intent = new
		 Intent(LotteryDetailActivity.this,JoinUsListActivity.class);
		 intent.putExtra(JoinUsListActivity.LUCKID, luckId);
		 startActivity(intent);
		 break;
		 case R.id.iv_none_refresh:
			 getPhaseShopDetail(mPhase);
			 break;
		default:
			break;
		}
	}
}
